﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="InitializeStorageAccountOperation.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.DeploymentManager.DeploymentOperations
{
    using System;
    using System.Linq;

    using AzureManagement.AzureDataContracts;

    using CloudBlitz.DeploymentManager.DeploymentWorkflow;

    public class InitializeStorageAccountOperation : DeploymentOperationBase
    {
        private readonly IAzureServiceClientsFactory azureServiceClientsFactory;

        public InitializeStorageAccountOperation(IAzureServiceClientsFactory azureServiceClientsFactory) : base(5)
        {
            this.azureServiceClientsFactory = azureServiceClientsFactory;
        }

        protected override OperationResult ExecuteOverride(DeploymentContext context)
        {
            var azureServiceManagementClient =
                this.azureServiceClientsFactory.CreateServiceManagementClient(context.AzureCredentials);

            try
            {
                this.RaiseProgressChangedEvent(0, string.Format("Initializing storage account \"{0}\"", context.StorageAccountName));

                var storageServices = azureServiceManagementClient.ListStorageAccounts().Result;

                if (!storageServices.Any(x => x.ServiceName.Equals(context.StorageAccountName)))
                {
                    var operationId = azureServiceManagementClient.CreateStorageAccount(
                                                                        context.StorageAccountName,
                                                                        context.StorageAccountName,
                                                                        context.StorageAccountName,
                                                                        null,
                                                                        context.Location,
                                                                        false).Result;

                    this.RaiseProgressChangedEvent(50, string.Format("Storage account \"{0}\" created, waiting for the operation to complete", context.StorageAccountName));

                    var operation = azureServiceManagementClient.WaitOperationForCompletion(operationId, TimeSpan.MaxValue);

                    if (operation.Status == OperationStatuses.Failed)
                    {
                        return new OperationResult(DeploymentOperationStatus.Failed, operation.Error.Message);
                    }

                    this.RaiseProgressChangedEvent(80, string.Format("Storage account \"{0}\" created, retrieving storage account keys", context.StorageAccountName));
                }
                else
                {
                    this.RaiseProgressChangedEvent(80, string.Format("Storage account \"{0}\" already exists, retrieving storage account keys", context.StorageAccountName));
                }

                var storageAccountKeys = azureServiceManagementClient.GetStorageAccountKeys(context.StorageAccountName).Result;

                context.ClusterDetails.StorageAccountName = context.StorageAccountName;
                context.ClusterDetails.StorageKey = storageAccountKeys.Primary;

                this.RaiseProgressChangedEvent(100, string.Format("Storage account \"{0}\" initialized", context.StorageAccountName));
                return OperationResult.Success;
            }
            catch (Exception e)
            {
                return ExceptionHelper.HandleException(e);
            }
        }
    }
}